package jfood.waiter;

import javax.swing.JOptionPane;

import jade.content.Concept;
import jade.content.ContentElement;
import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.content.onto.basic.Action;
import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.Property;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jfood.ontology.meal.Meal;
import jfood.ontology.meal.MealOntology;
import jfood.ontology.meal.ServeMealAction;
import jfood.ontology.meal.ServeMealAction.AnswerType;
import jfood.ontology.query.AskForMealAction;

public class AskForMealBehaviour extends OneShotBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1290682726600673305L;
	private String message;
	
	public AskForMealBehaviour(String message) {
		this.message = message;
	}

	
	@Override
	public void action() {
		AskForMealAction action = new AskForMealAction(message);
		ACLMessage msg = prepareMessageRequest();
		
		AID chef = getChef();
		
		if (chef == null)
		{
			JOptionPane.showMessageDialog((getAgent()).gui, "Wszyscy kucharze są aktualnie zajęci. Poczekaj chwilę", "Kucharze zajęci", JOptionPane.ERROR_MESSAGE);
			return;
		}

		fillContent(msg, new Action(chef, action));
		
		msg.addReceiver(chef);
		getAgent().send(msg);
		
		MessageTemplate messType = MessageTemplate.MatchPerformative(ACLMessage.INFORM);
		MessageTemplate ontoType = MessageTemplate.MatchOntology(MealOntology.NAME);
		
		ACLMessage response = myAgent.blockingReceive(MessageTemplate.and(messType,ontoType));
		
		ContentElement content = null;
		try {
			content = getAgent().getContentManager().extractContent(response);
		} catch (CodecException e) {
			e.printStackTrace();
		}catch (OntologyException e) {
			e.printStackTrace();
		}

		Concept conceptResponse = ((Action) content).getAction();

		System.out.println("message received");
				switch (response.getPerformative()) {
		case (ACLMessage.INFORM):
			if (conceptResponse instanceof ServeMealAction) 
			{
				ServeMealAction actionResponse = (ServeMealAction)conceptResponse;
				if(actionResponse.getType() == AnswerType.RECIPE)
				{
					Meal meal = actionResponse.getAskFor();
					System.out.println("RECIPE IS RECEIVED");
					System.out.println(meal.toString());
					String reply = "Zapytałeś o przepis na:" + meal.getName() + "\n";
					reply += "\nOto on: \n";
					reply += "Składniki: \n";
					for (Ingredient ingredient : meal.getIngredients()) {
						reply += ingredient.getName() + "\n";
					}
					reply += "\nPrzepis: \n";
					reply += meal.getRecipe().getContent() + "\n";
					
					getAgent().gui.printMessage(reply);
					
				}
				else if(actionResponse.getType() == AnswerType.PREPOSITIONS)
				{
					System.out.println("PREPOSITIONS IS RECEIVED");
					for(Meal meal: actionResponse.getResults())
					{
						System.out.println(meal.getName());
					}
					
					String reply = "Zapytałeś co możesz przygotować\n";
					reply += "Być może przygotujesz coś z tej listy: \n";
					for(Meal meal: actionResponse.getResults())
					{
						reply += meal.getName() + "\n";
					}
					reply += "\nSzef kuchni poleca: \n";
					Random generator = new Random(); 
					int i = generator.nextInt(actionResponse.getResults().size()) + 1;
					Meal meal = actionResponse.getResults().get(i);
					reply += meal.getName() +"\n\n";
					reply += "Składniki: \n";
					for (Ingredient ingredient : meal.getIngredients()) {
						reply += ingredient.getName() + "\n";
					}
					reply += "Przepis: \n\n";
					reply += meal.getRecipe().getContent() + "\n";
					
					getAgent().gui.printMessage(reply);
				}
				else if(actionResponse.getType() == AnswerType.NOTHING)
				{
					
					String reply = "Niestety nie potrafimy Ci pomóc\n";
					reply += "Zajrzyj do nas później, może się już tego nauczymy.";
					getAgent().gui.printMessage(reply);
					System.out.println("NOTHING WAS FOUND");
				}
			}
		}
	}
	
	private void fillContent(final ACLMessage message, Action action)
	{
		try {
			getAgent().getContentManager().fillContent(message, action);
		} catch (CodecException e) {
			e.printStackTrace();
		} catch (OntologyException e) {
			e.printStackTrace();
		}
	}
	
	private ACLMessage prepareMessageRequest()
	{
		WaiterAgent agent = getAgent();
		
		ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
		msg.setLanguage(agent.codec.getName());
		msg.setOntology(agent.queryOntology.getName());
		
		return msg;
	}
	
	public WaiterAgent getAgent() {
		return (WaiterAgent) super.getAgent();
	}
	
    private AID getChef()
    {
    	DFAgentDescription template = new DFAgentDescription();
		ServiceDescription templateSd = new ServiceDescription();
		templateSd.setType("meal-knowledge");
		templateSd.addProperties(new Property("country", "Poland"));
		template.addServices(templateSd);
     	try {
     		DFAgentDescription[] result = DFService.search(getAgent(), template);
     		if (result.length > 0)
     		{
     			return result[0].getName();
     		}
    	}
    	catch (FIPAException ex) {
    		ex.printStackTrace();
    	}
		return null;
    }

}
